<template>
  <div>
    <h3 align="center">购物车</h3>
    <goods
      v-for="(goods, index) in goodsList"
      :key="index"
      :goods="goods"
      @subGoods="subGoods"
      @addGoods="addGoods"
    ></goods>
    <div>商品的总价：{{ total }}</div>
  </div>
</template>

<script>
import goodsList from '@/api/goods'
import Goods from '@/components/Goods.vue'
export default {
  data() {
    return { goodsList: goodsList }
  },
  mounted() {
    console.log(this.goodsList)
  },
  computed: {
    total() {
      var sum = 0
      this.goodsList.forEach((goods) => {
        sum += goods.price * goods.num
      })
      return sum
    },
  },
  methods: {
    addGoods(id) {
      //从goodsList中找到goods，对num+1
      const goods = this.goodsList.find((item) => item.id == id)
      goods.num = goods.num + 1
    },
    subGoods(id) {
      const goods = this.goodsList.find((item) => item.id == id)
      goods.num = goods.num - 1
    },
  },
  components: {
    Goods,
  },
}
</script>

<style lang="scss" scoped></style>
